/**
 * 生成任务详情相关页面柱状图
 */

// 获取字符串长度
function getLength(val) {
  var str = new String(val);
  var bytesCount = 0;
  for (var i = 0, n = str.length; i < n; i++) {
    var c = str.charCodeAt(i);
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      bytesCount += 1;
    } else {
      bytesCount += 2;
    }
  }
  return bytesCount;
}
export default ({ x, y, color, transpose = false, limitXLabelLength }) => {
  color = [].concat(color);

  if (transpose) {
    x = x.reverse();
    y = y.reverse();
    color = color.reverse();
  }

  let maxValue = Math.max(...y);
  let option = {
    tooltip: {
      formatter: function (params) {
        const arr = params.name.split('||%%');
        const res = '业务系统URL：' + arr[0] + '<br/>' + '业务系统名称：' + arr[1];
        return res;
      },
    },
    color: color,
    grid: {
      top: '5%',
      left: '3%',
      right: '5%',
      bottom: '4%',
      borderColor: '#ff0000',
      containLabel: true,
    },
    xAxis: {
      triggerEvent: true,
      type: 'category',
      axisTick: false,
      axisLabel: {
        color: '#686C78',
        formatter: function (value) {
          const sepUrlName = value.split('||%%');
          let url = sepUrlName[0];
          let name = sepUrlName[1];
          if (limitXLabelLength && getLength(url) > limitXLabelLength) {
            const index = (url.length / getLength(url)) * limitXLabelLength;
            url = url.slice(0, parseInt(index)) + '...';
          }
          if (limitXLabelLength && getLength(name) > limitXLabelLength) {
            const index = (name.length / getLength(name)) * limitXLabelLength;
            name = name.slice(0, parseInt(index)) + '...';
          }
          return url + '\n' + name;
        },
      },
      axisLine: {
        lineStyle: {
          color: '#E6EAEF',
        },
      },
      data: x,
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: {
        lineStyle: {
          color: '#E6EAEF',
        },
      },
      interval: Math.ceil(maxValue / 6),
      axisLabel: {
        color: '#686C78',
      },
    },
    series: {
      type: 'bar',
      barMaxWidth: 16,
      data: y.map((value, index) => {
        let tempColor = color[index] || color[color.length - 1];
        if (Array.isArray(tempColor)) {
          tempColor = {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y: 1,
            colorStops: [
              {
                offset: 0,
                color: tempColor[0],
              },
              {
                offset: 1,
                color: tempColor[1],
              },
            ],
          };
        }
        return {
          value,
          itemStyle: {
            color: tempColor,
          },
        };
      }),
    },
  };

  if (transpose) {
    [option.xAxis, option.yAxis] = [option.yAxis, option.xAxis];
  }

  return option;
};
